package game.core.phases 
{
	import flash.events.Event;
	import flash.geom.Point;
	import game.core.Player;
	import game.gui.Camera;
	import game.objects.Building;
	/**
	 * ...
	 * @author Sulus Ltd.
	 */
	public class AutoActionPhase extends TurnPhase
	{
		private var playerBuildings:Array;
		private var currentBuildingIdx:int;
		private var active:Boolean = true;
		private var actionsFinished:Boolean = false;
		private var idle:Boolean = false;
		private var idleCounter:int = 0;
		
		
		public function AutoActionPhase() 
		{
			name = "авто-действия";
		}
		
		override public function Start():void 
		{
			trace("AutoActionPhase phase begins");
			
			var player:Player = papa.currentPlayer;
			if (!player) 
			{
				EndPhase();
				return;
			}
			var buildings:Array = papa.buildings;
			playerBuildings = [];
			for each (var building:Building in buildings)
			{
				if (building.player == player && building.autoActions.length>0)
				playerBuildings.push(building);
			}
			
			if (playerBuildings.length == 0) 
			{
				EndPhase();
				return;
			}
			
			currentBuildingIdx = 0;
			SelectBuilding(currentBuildingIdx);
		}
		
		
		private function SelectBuilding(idx:int):void 
		{
			if (idx < 0) idx = playerBuildings.length - 1;
			if (idx >= playerBuildings.length) idx = 0;
			
			currentBuildingIdx = idx;
			
			var building:Building = playerBuildings[idx];
			papa.world.gui.camera.MoveTo(new Point(building.x, building.y));
			active = false;
			papa.world.gui.camera.eventDispatcher.addEventListener(Camera.EVENT_MOVE_COMPLETE, OnCameraFocused);
		}
		
		private function OnCameraFocused(e:Event):void 
		{
			active = true;
			papa.world.gui.camera.eventDispatcher.removeEventListener(Camera.EVENT_MOVE_COMPLETE, OnCameraFocused);
		}	
		
		
		override public function Update():void 
		{
			if (idle)
			{
				if (idleCounter-- <= 0)
				{
					idle = false;
					
					
					if (currentBuildingIdx < playerBuildings.length)
					{
						SelectBuilding(currentBuildingIdx);
					}
					else
					{
						active = false;
						actionsFinished = true;
					}
					
				}
			} else
			if (active)
			{
				if ((playerBuildings[currentBuildingIdx] as Building).DoAction())
				{
					currentBuildingIdx++;
				}
				idle = true;
				idleCounter = 30;
				
			} else
			if (actionsFinished)
			{
				EndPhase();
				actionsFinished = false;
			}
		}
		
		override public function Finish():void 
		{
			trace("AutoActionPhase phase ends");
			
			papa.world.gui.camera.eventDispatcher.removeEventListener(Camera.EVENT_MOVE_COMPLETE, OnCameraFocused);
		}		
		
	}

}